import { toast } from '../../../utils/util'
import { fastInsureSubtractType } from '../../utils/map.js'
import {
    getInsureData,
    getDispatchList,
    createQrproject,
    getQrprojectDetail,
    switchIsInvalid
} from '../../api/long-insure'
Page({
    /**
     * 页面的初始数据
     */
    data: {
        title: '',
        projectName: '',
        disableprojectName: false,
        plan: {
            list: [],
            label: '',
            value: '',
            code: '',
            index: 0,
            disable: false
        },
        insureCompany: {
            show: false,
            list: [],
            label: '',
            value: '',
            index: [0],
            disable: false
        },
        occupation: {
            hint:
                '1、仅承保视频中的对应风险等级工种，其它工种请再提供视频确认2、超风险投保警示:严格按照实际工种对应风险等级进行投保，严禁超风险投保，否则保险公司有权拒赔。如将4类及以上工种投保至1-3类工种属于超风险投保工种',
            showHint: false,
            isCheck: false,
            list: [],
            label: '',
            value: '',
            index: 0,
            disable: false,
            level: ''
        },
        subtractInsure: {
            list: [
                {
                    label: '手动减保',
                    value: 0,
                },
                // {
                //     label: '1天后自动减保',
                //     value: 1,
                // },
            ],
            value: 0,
            label: '手动减保',
            disable: false
        },
        detailId: '',
        isEdit: false,
        isInvalid: 0,
        isChangeStatus: false,
        hint: '',
        status: 0,
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options?.id) {
            this.setData({
                detailId: options.id
            })
            this.getDetail()
        }
        this.setData({
            isEdit: !!options.id,
            title: options.id ? '编辑' : '创建投保码'
        })
        this.getPlanList()
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {},
    // 输入事件
    onInput(ev) {
        const dataset = ev.currentTarget.dataset
        this.setData({
            [dataset.prop]: ev.detail.value.trim(),
        })
    },
    // 获取方案列表 获取所有的数据 需要过滤出type为5（立即生效）的方案
    async getPlanList() {
        const res = await getInsureData()
        const fastPlan = res?.companyPlans?.filter((i) => i.type === 5) || []
        this.setData({
            ['plan.list']: fastPlan,
        })
    },
    // 选择方案
    async onSelectPlan(ev) {
        const value = ev.detail.value
        const cur = this.data.plan.list[value]
        if (cur) {
            this.setData({
                ['plan.index']: value,
                ['plan.id']: cur.id,
                ['plan.value']: cur.insurCompany,
                ['plan.label']: cur.insurCompanyPlanName,
                ['plan.code']: cur.insurCompanyPlanCode,
            })
            await this.getInsureCompanyList()
        }
    },
    // 获取派遣单位列表
    async getInsureCompanyList() {
        const res = await getDispatchList({
            pageNum: 1,
            pageSize: 100,
            status: 1,
            insurCompany: this.data.plan.value,
            planCode: this.data.plan.code,
            isGetArea: 1,
        })
        this.setData({
            ['insureCompany.list']: res.list,
        })
    },
    // 打开派遣单位弹框
    onShowSelectInsureCompany() {
        if (this.data.insureCompany.disable) return
        this.setData({
            ['insureCompany.show']: true,
        })
    },
    // 关闭派遣单位弹框
    onInsureCompanyClose() {
        this.setData({
            ['insureCompany.show']: false,
        })
    },
    // 选择派遣单位
    onConfirmInsureCompany() {
        const cur = this.data.insureCompany.list[this.data.insureCompany.index]
        if (!cur.occupationList.length) {
            wx.showModal({
                title: '提示',
                content: '很抱歉，您当前所选择派遣单位的可用工种，不在该方案的承保范围内，请联系您的专属客户经理。',
                showCancel: false
            })
            return
        }
        if (cur.isForbidden) {
            toast('已被管理员禁用')
            return
        } else if (cur.isBlacklist) {
            toast('已被系统禁用')
            return
        } else {
            this.setData({
                ['insureCompany.label']: cur.serveCompanyName,
                ['insureCompany.value']: cur.serveCompanyId,
                ['insureCompany.show']: false,
                ['insureCompany.showHint']: true,
                ['occupation.list']: cur.occupationList,
                ['occupation.showHint']: true,
                ['occupation.index']: -1,
                ['occupation.label']: ''
            })
        }
    },
    // 派遣单位change触发
    onInsureCompanyChange(ev) {
        this.setData({
            ['insureCompany.index']: ev.detail.value,
        })
    },
    // 选择工种
    onSelectOccupation(ev) {
        const value = ev.detail.value
        const cur = this.data.occupation.list[value]
        if (cur) {
            this.setData({
                ['occupation.index']: value,
                ['occupation.value']: cur.id,
                ['occupation.label']: cur.name,
                ['occupation.level']: cur.level
            })
        }
    },
    onOccupationHintChange(ev) {
        this.setData({
            ['occupation.isCheck']: !!ev.detail.value.length
        })
    },
    // 选择减保方式
    onSelectSubtractInsure(ev) {
        const value = ev.detail.value
        const cur = this.data.subtractInsure.list[value]
        if (cur) {
            this.setData({
                ['subtractInsure.index']: value,
                ['subtractInsure.value']: cur.value,
                ['subtractInsure.label']: cur.label,
            })
        }
    },
    // 生成投保二维码
    async onConfirm() {
        const query = {
            projectName: this.data.projectName,
            companyPlanId: this.data.plan.id,
            serveCompanyId: this.data.insureCompany.value,
            serveCompanyName: this.data.insureCompany.label,
            occupationId: this.data.occupation.value,
            occupationName: this.data.occupation.label,
            occupationLevel: this.data.occupation.level,
            type: this.data.subtractInsure.value,
        }
        const map = {
            projectName: '请输入投保码名称',
            companyPlanId: '请选择方案',
            serveCompanyId: '请选择派遣单位',
            occupationId: '请选择工种',
            type: '请选择减保方式',
        }
        
        for (const key in map) {
            if (
                query[key] === null ||
                query[key] === '' ||
                query[key] === undefined
            ) {
                toast(map[key])
                return
            }
        }
        if (!this.data.occupation.isCheck) {
            toast('请勾选特别约定')
            return
        }
        const res = await createQrproject(query)
        this.setData({
            detailId: res
        })
        this.toDetail()
    },
    toDetail() {
        wx.navigateTo({
            url:
                `/packageLongInsure/pages/fast-insure-detail/fast-insure-detail?id=${this.data.detailId}`,
        })
    },
    async getDetail() {
        const res = await getQrprojectDetail(this.data.detailId)
        this.setData({
            projectName: res.projectName,
            disableprojectName: true,
            isInvalid: res.isInvalid,
            ['plan.disable']: true,
            ['plan.label']: res.companyPlanName,
            ['plan.id']: res.companyPlanId,
            ['plan.code']: res.insurCompanyPlanCode,
            ['insureCompany.disable']: true,
            ['insureCompany.label']: res.serveCompanyName,
            ['insureCompany.value']: res.serveCompanyId,
            ['occupation.disable']: true,
            ['occupation.label']: res.occupationName,
            ['occupation.value']: res.occupationId,
            ['subtractInsure.disable']: true,
            ['subtractInsure.label']: fastInsureSubtractType[res.type],
            ['subtractInsure.value']: res.type
        })
    },

    async onChangeStatus(ev) {
        const dataset = ev.currentTarget.dataset
        const hint = dataset.status === '1' ? '停用后当前投保码将失效，确定停用？' : '确定启用当前投保码？'
        this.setData({
            isChangeStatus: true,
            hint,
            status: Number(dataset.status)
        })

        // confirm(hint).then(async (res) => {
        //     console.log(2121, res)

        // })
    },
    onHandleCancel() {
        this.setData({
            isChangeStatus: false,
        })
    },
    async onHandleConfirm() {
        await switchIsInvalid({
            id: this.data.detailId,
            isInvalid: this.data.status
        })
        toast('修改成功')
        this.onHandleCancel()
        this.getDetail()
    }
})
